from django.shortcuts import render, redirect

# Create your views here.
from .models import BrandInfo


def show_index(request):
    brands = BrandInfo.objects.all()
    return render(request, 'brand/commodity-brand.html', {'brands': brands})


def show_add_index(request):
    return render(request, 'brand/brandAdd.html')


def add_brand(request):
    if request.POST:
        # 获取请求参数
        brandname = request.POST.get('brandname','')
        brandID = request.POST.get('ID','')
        #print(brandname)
       #print(brandID)
        # 查询数据库
        if brandname and brandID:
            brandcount = BrandInfo.objects.filter(name=brandname, id=brandID).count()
            if brandcount == 0:
                #print(brandcount)
                # 创建模型对象
                brand = BrandInfo(name=brandname, id=brandID)
                # 插入数据库
                brand.save()
                return redirect('/brand/show')
        return redirect('/brand/add')



def show_update_index(request,id):
    brand = BrandInfo.objects.get(id=id)
    return render(request, 'brand/brandUpdate.html',{'brand': brand})


def update_brand(request):
    if request.POST:
        oldname =request.POST.get('oldname')
        oldid = request.POST.get('oldid')
        brand = BrandInfo.objects.get(id=oldid)
        print(brand.id)
        print(brand.name)
        # 获取请求参数
        brandname = request.POST.get('brandname', '')
        brandID = request.POST.get('ID', '')
        brand.id = brandID
        brand.name = brandname
        print(brandname)
        print(brandID)
        brand.save()
        return redirect('/brand/show/')


def delete_brand(request,id):
    print(id)
    brand = BrandInfo.objects.get(id=id)
    brand.delete()
    return redirect('/brand/show/')